<template>
  <div>
    <!-- 搜索栏 -->
    <el-form v-show="showSearch" :inline="true" :model="queryParams">
      <el-form-item label="姓名">
        <el-input v-model="queryParams.name" clearable placeholder="请输入学生姓名"
                  style="width: 150px" @input="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <svg-icon icon-file-name="white-search" style="color: #1abc9c"></svg-icon>
          搜索
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <el-row :gutter="10" style="margin-bottom: 15px">
      <el-col :span="1.5">
        <el-button :disabled="studentIdList.length === 0" icon="Delete" plain type="danger"
                   @click="handleBatchDelete">批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-plus" plain type="primary" @click="studentInfoDialogVisible = true;isEditing = false;">
          新增
        </el-button>
      </el-col>
      <refresh-and-hide @refresh="handleRefresh" @toggle-search="handleToggleSearch"/>
    </el-row>
    <div class="scroll-container">
      <!-- 表格展示 -->
      <el-table v-loading="loading" :data="studentList" border @sort-change="handleSortChange"
                @selection-change="handleSelectionChange">
        <!-- 表格选择列 -->
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <!--缩略图-->
        <el-table-column align="center" label="头像" prop="avatarUrl" width="180">
          <template #default="scope">
            <el-image :lazy="true" :src="scope.row.avatarUrl" class="image-cover" fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" label="姓名" prop="name"></el-table-column>
        <el-table-column align="center" label="学号" prop="studentNum"></el-table-column>
        <el-table-column align="center" label="年级" prop="grade">
          <template #default="scope">
            {{ ['大一', '大二', '大三', '大四'][scope.row.grade - 1] }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="已修学分" prop="learnCredits" sortable="custom">
        </el-table-column>
        <el-table-column align="center" label="注册时间" prop="createTime" sortable>
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 更新时间 -->
        <el-table-column align="center" label="信息更新时间" prop="updateTime" sortable width="130">
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.updateTime }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column align="center" label="操作" width="220">
          <template #default="scope">
            <el-button class="sdf" link type="primary" @click="handleEdit(scope.row)">
              <svg-icon icon-file-name="edit"></svg-icon>
              编辑
            </el-button>
            <el-button class="sd" link type="danger" @click="handleDelete(scope.row.studentId)">
              <svg-icon icon-file-name="delete"></svg-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <pagination v-if="total > 0" :limit="pagInfo.pageSize" :page="pagInfo.currentPage" :total="total"
                style="float: right;" @pagination="getStudentInfoList"
                @update_limit="pagInfo.pageSize = $event"
                @update_page="pagInfo.currentPage = $event"/>
    <el-dialog :title="GTitle" :visible.sync="studentInfoDialogVisible" width="50%">
      <el-form ref="studentInfoForm" :model="studentInfoForm" :rules="studentRules">
        <el-form-item :label-width="formLabelWidth" label="姓名:" prop="name">
          <el-input v-model="studentInfoForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="学号:" prop="studentNum">
          <el-input v-model="studentInfoForm.studentNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="年级:" prop="grade">
          <el-select v-model="studentInfoForm.grade" placeholder="请选择">
            <el-option label="大一" value="1"></el-option>
            <el-option label="大二" value="2"></el-option>
            <el-option label="大三" value="3"></el-option>
            <el-option label="大四" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="头像">
          <ImageUpload ref="studentImage" :limit="1"
                       @update-file-list="addStudentInfoHandleUpdateStudentAvatar"></ImageUpload>
        </el-form-item>
        <el-form-item v-if="!isEditing" :label-width="formLabelWidth" label="密码" prop="password">
          <el-input v-model="studentInfoForm.password" autocomplete="off" placeholder="请输入密码"
                    type="password"></el-input>
        </el-form-item>
        <!-- 新增修改密码项 -->
        <el-form-item v-else :label-width="formLabelWidth" label="修改密码:">
          <el-button @click="showStudentPasswordInput = !showStudentPasswordInput">修改密码</el-button>
          <el-input v-if="showStudentPasswordInput" v-model="studentInfoForm.password" autocomplete="off"
                    placeholder="请输入新密码" type="password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="studentInfoDialogVisible = false;">取消</el-button>
        <el-button type="primary" @click="saveStudentInfo()">保存</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import refreshAndHide from "@/common/refreshAndHide.vue";
import Pagination from "@/common/pagination.vue";
import {
  addStudentInfo,
  deleteStudentInfo,
  deleteStudentOnList,
  editStudentInfo,
  getStudentList
} from "@/apis/admin";
import ImageUpload from "@/common/ImageUpload.vue";

export default {
  // 组件注册，允许在模板中使用导入的组件
  components: {
    ImageUpload,
    Pagination, // 分页组件
    refreshAndHide // 刷新和隐藏组件
  },
  // 组件的响应数据对象
  data() {
    return {
      studentRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度应在 2 到 20 个字符之间', trigger: 'blur' }
        ],
        studentNum: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]+$/, message: '学号只能包含字母和数字', trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur', condition: () => !this.isEditing || this.showStudentPasswordInput },
          { min: 6, message: '密码长度不能小于 6 位', trigger: 'blur', condition: () => !this.isEditing || this.showStudentPasswordInput }
        ]
      },
      // 控制搜索表单显示的布尔值
      showSearch: true,
      // 搜索参数对象
      queryParams: {
        name: '', // 课程名
      },
      //分页信息
      pagInfo: {
        currentPage: 1,
        pageSize: 10
      },
      // 存储选中的课程ID列表
      studentIdList: [],
      // 存储课程列表的数组
      studentList: [],
      // 控制表格加载状态的布尔值
      loading: false,
      // 存储总课程数量的变量
      total: 0,

      isEditing: false, // 控制是否处于编辑状态
      studentInfoDialogVisible: false, // 控制增加学生信息窗口的显示
      showStudentPasswordInput: false, // 控制是否显示修改密码输入框
      studentInfoForm: { // 添加表单的数据模型
        studentId: '',
        studentNum: '',
        avatarUrl: '',
        name: '',
        grade: '',
        password: ''
      },
      formLabelWidth: '120px', // 表单标签宽度
    };
  },
  methods: {
    saveStudentInfo() {
      this.$refs.studentInfoForm.validate((valid) => {
        if (valid) {
          if (!this.isEditing) {
            let data = {
              studentNum: this.studentInfoForm.studentNum,
              avatarUrl: this.studentInfoForm.avatarUrl,
              name: this.studentInfoForm.name,
              grade: this.studentInfoForm.grade,
              password: this.$common.encrypt(this.studentInfoForm.password)
            }
            addStudentInfo(data).then(res => {
              if (res.data.code === 1) {
                this.$message({
                  message: "新增成功",
                  type: "success"
                });
                this.studentInfoDialogVisible = false;
                this.getStudentInfoList();
              }
            })
          } else {
            let data = {
              studentId: this.studentInfoForm.studentId,
              studentNum: this.studentInfoForm.studentNum,
              avatarUrl: this.studentInfoForm.avatarUrl,
              name: this.studentInfoForm.name,
              grade: this.studentInfoForm.grade,
              password: (!this.$common.isEmpty(this.studentInfoForm.password)) ? this.$common.encrypt(this.studentInfoForm.password) : null
            }
            editStudentInfo(data).then(res => {
              if (res.data.code === 1) {
                this.$message({
                  message: "编辑成功",
                  type: "success"
                });
                this.studentInfoDialogVisible = false;
                this.getStudentInfoList();
              }
            })
            this.isEditing = false;
          }
        } else {
          this.$message.error('表单中有错误，请修正后再尝试保存');
        }
      });
    },
    addStudentInfoHandleUpdateStudentAvatar(newFileList) {
      // 使用传递过来的 fileList 更新父组件的 parentFileList
      // 遍历 newFileList 数组
      newFileList.forEach(file => {
        // 将每个文件的 URL 添加到 imageUrls 数组中
        this.studentInfoForm.avatarUrl = file.url;
      });
    },
    // 处理编辑按钮点击事件
    handleEdit(data) {
      this.isEditing = true;
      this.studentInfoForm = data;
      this.studentInfoDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.studentImage.fileList = [];
        this.$refs.studentImage.setFileList(data.avatarUrl)
      })
    },
    // 前端排序函数
    handleSortChange({prop, order}) {
      if (!order) {
        // 如果没有排序顺序，可能是恢复到未排序状态
        this.getStudentInfoList();
        return;
      }

      this.studentList.sort((a, b) => {
        if (order === 'ascending') {
          return a[prop] - b[prop]; // 升序排序
        } else {
          return b[prop] - a[prop]; // 降序排序
        }
      });
    },
    // 处理搜索显示/隐藏的逻辑
    handleToggleSearch() {
      this.showSearch = !this.showSearch;
    },
    // 处理刷新数据的逻辑
    handleRefresh() {
      this.getStudentInfoList();
      this.$message.success('列表已刷新');
    },
    // 搜索课程的方法
    handleQuery() {
      this.loading = true;
      // 重置当前页为第一页
      this.pagInfo.currentPage = 1;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = {
        name: this.queryParams.name,
        teacherName: this.queryParams.teacherName,
      }
      const DTOdata = {
        pagination,
        queryParams//只有搜索时才会带上
      }
      getStudentList(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((article) => {
            article.createTime = this.$common.dateFormat(article.createTime);
            article.updateTime = this.$common.dateFormat(article.updateTime);
          });
          this.studentList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    // 处理表格行选择事件
    handleSelectionChange(selection) {
      this.studentIdList = selection.map(item => item.studentId);
    },
    //批量删除方法
    handleBatchDelete() {
      if (this.studentIdList.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择要删除的课程'
        });
        return;
      }
      // 确认弹窗
      this.$confirm('确定要删除选中的学生信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          ids: this.studentIdList
        }
        // 这里发送删除请求
        deleteStudentOnList(data).then(res => {
          if (res.data.code === 1) {
            this.$message.success(res.data.data);
            this.getStudentInfoList();
          } else {
            this.$message.error(res.data.msg);
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除单个学生的方法
    handleDelete(id) {
      if (id) {
        this.$confirm('确定要删除该学生吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const data = {
            studentId: id
          }
          deleteStudentInfo(data).then(res => {
            if (res.data.code === 1) {
              this.$message.success(res.data.data);
              this.getStudentInfoList();
            } else {
              this.$message.error(res.data.msg);
            }
          })

        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '已取消删除'
          });
        });
      }
    },
    // 获取课程列表的方法
    async getStudentInfoList() {
      this.loading = true;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = null;
      const DTOdata = {
        pagination,
        queryParams
      }
      await getStudentList(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((course) => {
            course.createTime = this.$common.dateFormat(course.createTime);
            course.updateTime = this.$common.dateFormat(course.updateTime);
          });
          this.studentList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    }
  },
  created() {
    this.getStudentInfoList();
  },
  computed: {
    GTitle() {
      return this.isEditing ? '编辑学生' : '新增学生'
    }
  }
};
</script>

<style scoped>

.scroll-container {
  max-height: 646px; /* 您可以根据需要调整这个值 */
  overflow-y: auto;
}

.sdf {
  background: transparent;
  border-color: transparent;
  color: #76d7ff;
}

.sd {
  background: transparent;
  border-color: transparent;
  color: #fa1224;
}

.image-cover {
  width: 100px;
  height: 60px;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;

  .image-slot {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    color: #909399;
  }
}

.time {
  display: flex;
  align-items: center;
}
</style>

